﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace AzureReader.BLL
{
   public  class FeedSubscriptionsManager
    {
       static public void AddNewSubscription(string userID, string feedUrl)
       {
           try
           {
               using (AzureReaderDataContext context = new AzureReaderDataContext())
               {
                   var feed = (from f in context.Feeds
                               where f.FeedUrl == feedUrl
                               select f).FirstOrDefault();
                   if (feed == null)
                   {
                       feed = new Feed();
                       feed.FeedID = Guid.NewGuid();
                       feed.FeedUrl = feedUrl;
                       context.Feeds.InsertOnSubmit(feed);
                   }
                   FeedSubscription fs = new FeedSubscription();
                   fs.SubscriptionID = Guid.NewGuid();
                   fs.UserID = userID;
                   fs.Feed = feed;
                   fs.SubscriptionDate = DateTime.Now;
                   context.SubmitChanges();
               }
           }
           catch (Exception ex)
           {
               Logger.LogException(ex);
           }
       }

       static public FeedItem[] GetFeedItems(string feedUrl)
       {
           try
           {
               using (AzureReaderDataContext db = new AzureReaderDataContext())
               {
                  return  (from fi in db.FeedItems
                               where fi.Feed.FeedUrl == feedUrl
                               orderby fi.PublishDate descending
                               select fi).ToArray();
               }
           }
           catch (Exception ex)
           {
               Logger.LogException(ex);
               return null;
           }
       }


       static public vwSubscription[] GetUserSubscriptions(string userID)
       {
           using (AzureReaderDataContext context = new AzureReaderDataContext())
           {

            return    (from s in context.vwSubscriptions
                        where s.UserID == userID
                
                select s).ToArray();
           }
       }
    }
}
